﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    public class EndFuncParser : ILineParser
    {
        private static readonly Regex EndSubPattern =
            new Regex(
                @"^End Function",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            var match = EndSubPattern.Match(lineContent);
            success = match.Success;
            if (!success) return lineContent;
            var status = statuses.Peek();
            if (status.CurrentState != State.FuncDef)
            {
                throw new Exception();
            }
            statuses.Pop();
            if (lineClosed)
            {
                throw new Exception();
            }
            lineClosed = true;
            return "}";
        }
    }
}
